﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BizCollegeWebApp.Models;
using System.IO;
using System.Net.Mime;

namespace BizCollegeWebApp.Controllers
{
    public class CourseController : Controller
    {
        // GET: /Course/
        BizCollegeDBDataContext db = new BizCollegeDBDataContext();

        public ActionResult Index(string SearchTerm)
        {
            if (string.IsNullOrEmpty(SearchTerm))
            {
                ViewBag.SearchTerm = string.Empty;
            }
            else
            {
                ViewBag.SearchTerm = SearchTerm;
            }

            return View(this.db.GetCourses(SearchTerm).AsEnumerable());
        }

        //
        // GET: /Course/Details/5
        public ActionResult ViewCourse(int id)
        {
            Course c = this.db.Courses.FirstOrDefault(cc => cc.CourseID == id);
            if (c == null)
            {
                return RedirectToAction("Index");
            }
            if (TempData["message"] != null)
            {
                ViewBag.Message = TempData["message"].ToString();
            }
            else
            {
                ViewBag.Message = c.CourseName;
            }
            return View("ViewCourse", c);
        }

        public ActionResult ViewSection(int id)
        {
            CourseContent cc = this.db.CourseContents.FirstOrDefault(c => c.ContentID == id);

            if (cc == null)
            {
                return RedirectToAction("Index");
            }

            return View(cc);
        }


        // GET: /Course/Create
        public ActionResult Create()
        {
            Course crs = new Course();
            return View(crs);
        }

        //
        // POST: /Course/Create
        [HttpPost]
        public ActionResult Create(Course course)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    course.ViewedNumber = 0;
                    course.CompletedNumber = 0;
                    course.AvgTimeSpendInMins = 0;

                    course.CourseStateID = this.db.GetUnderReviewCourseState();

                    this.db.Courses.InsertOnSubmit(course);
                    this.db.SubmitChanges();

                    return RedirectToAction("AddContent", new { CourseID = course.CourseID, FirstContent = true });
                }
                return View(course);
            }
            catch
            {
                return View(course);
            }
        }

        [HttpGet]
        public ActionResult AddContent(int CourseID, bool FirstContent = false)
        {
            CourseContent cc = new CourseContent()
            {
                CourseID = CourseID
            };
            if (FirstContent)
            {
                ViewBag.Message = "The course description is succefully added. Now you can add sections of the course";
            }
            else
            {
                ViewBag.Message = "Content is succesfully added. Now you can add another section";
            }
            return View(cc);
        }

        [HttpPost]
        public ActionResult AddContent(CourseContent content, HttpPostedFileBase file)
        {
            ViewBag.Message = "Fix the validation failures and try again";
            try
            {
                if (ModelState.IsValid)
                {
                    if (file != null && file.ContentLength > 0)
                    {
                        content.MimeType = file.ContentType;
                        content.FileName = Path.GetFileName(file.FileName);

                        Stream fileStream = file.InputStream;
                        int fileLength = file.ContentLength;
                        byte[] fileData = new byte[fileLength];
                        fileStream.Read(fileData, 0, fileLength);
                        content.Content = fileData;
                    }
                    else
                    {
                        ModelState.AddModelError("file", "Please select a file to upload");
                        return View(content);
                    }

                    this.db.CourseContents.InsertOnSubmit(content);
                    this.db.SubmitChanges();

                    return RedirectToAction("AddContent", new { CourseID = content.CourseID, FirstContent = false });
                }
                return View(content);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("ex", ex);
                return View(content);
            }
        }


        //
        // GET: /Course/Edit/5

        [HttpGet]
        public ActionResult EditCourse(int id)
        {
            Course c = this.db.Courses.FirstOrDefault(cc => cc.CourseID == id);
            if (c == null)
            {
                return RedirectToAction("Index");
            }
            return View(c);
        }

        [HttpPost]
        public ActionResult EditCourse(int id, Course vCourse)
        {
            Course c = this.db.Courses.FirstOrDefault(cc => cc.CourseID == id);
            if (c == null)
            {
                return RedirectToAction("Index");
            }
            try
            {
                if (ModelState.IsValid)
                {
                    c.CourseName = vCourse.CourseName;
                    c.CourseDesciption = vCourse.CourseDesciption;
                    c.CourseStateID = this.db.GetUnderReviewCourseState();

                    this.db.SubmitChanges();

                    int next = c.GetFirstContentId();
                    if (next != -1)
                    {
                        return RedirectToAction("EditSection", new { id = next });
                    }
                    else
                    {
                        return RedirectToAction("Index");
                    }
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("ex", ex);
            }
            return View(c);
        }

        [HttpGet]
        public ActionResult EditSection(int id)
        {
            CourseContent cc = this.db.CourseContents.FirstOrDefault(c => c.ContentID == id);
            if (cc == null)
            {
                return RedirectToAction("Index");
            }
            return View(cc);
        }

        [HttpPost]
        public ActionResult EditSection(CourseContent ccView, HttpPostedFileBase file)
        {
            CourseContent dbCc = this.db.CourseContents.FirstOrDefault(c => c.ContentID == ccView.ContentID);
            if (dbCc == null)
            {
                return RedirectToAction("Index");
            }
            try
            {
                if (ModelState.IsValid)
                {
                    if (file != null && file.ContentLength > 0)
                    {
                        dbCc.MimeType = file.ContentType;
                        dbCc.FileName = Path.GetFileName(file.FileName);

                        Stream fileStream = file.InputStream;
                        int fileLength = file.ContentLength;
                        byte[] fileData = new byte[fileLength];
                        fileStream.Read(fileData, 0, fileLength);
                        dbCc.Content = fileData;
                    }

                    dbCc.SectionDescription = ccView.SectionDescription;
                    dbCc.SectionName = ccView.SectionName;

                    this.db.SubmitChanges();

                    int nextId = dbCc.Course.GetNextContentId(ccView.ContentID);
                    if (nextId == -1)
                    {
                        return RedirectToAction("Index");
                    }
                    else
                    {
                        return RedirectToAction("EditSection", new { id = nextId });
                    }
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("ex", ex);
            }
            ccView.Course = dbCc.Course;
            ccView.FileName = dbCc.FileName;
            return View(ccView);
        }


        public ActionResult Enroll(int id)
        {
            try
            {
                ViewBag.Message = string.Empty;
                Enrollment dbEn = this.db.Enrollments.FirstOrDefault(e => e.CourseID == id && e.UserID == Current.User.ID);
                if (dbEn == null)
                {
                    Enrollment en = new Enrollment()
                    {
                        CourseID = id,
                        UserID = Current.User.ID,
                        StartDate = DateTime.Now,
                        EndDate = DateTime.Now,
                        IsCompleted = false
                    };

                    this.db.Enrollments.InsertOnSubmit(en);
                    this.db.SubmitChanges();
                    TempData["message"] = "You have successfully enrolled for the course. Now you can browse it.";
                }
                else if (dbEn.IsCompleted)
                {
                    TempData["message"] = "You have already completed this course. You can browse it without registering again.";
                }
                else
                {
                    TempData["message"] = "You have already enrolled to this course. You can browse it";
                }

                return RedirectToAction("ViewCourse", new { id = id });
            }
            catch
            {
                return RedirectToAction("Index");
            }
        }


        public ActionResult Complete(int id)
        {

            try
            {
                Enrollment dbEn = this.db.Enrollments.FirstOrDefault(e => e.CourseID == id && e.UserID == Current.User.ID);
                if (dbEn == null)
                {
                    TempData["message"] = "Please enroll to this course before trying to complete it";
                }

                if (dbEn.IsCompleted)
                {
                    TempData["message"] = "You alredy completed this course";
                }

                dbEn.IsCompleted = true;
                dbEn.EndDate = DateTime.Now;

                this.db.SubmitChanges();

                TempData["message"] = "Congratulations. You have succefully completed this course.";
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("ex", ex.Message);
            }
            return RedirectToAction("ViewCourse", new { id = id });
        }
        //
        // GET: /Course/Delete/5
        public ActionResult Delete(int id)
        {
            Course c = this.db.Courses.FirstOrDefault(cc => cc.CourseID == id);
            if (c == null)
            {
                return RedirectToAction("Index");
            }

            return View(c);
        }

        //
        // POST: /Course/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            Course c = this.db.Courses.FirstOrDefault(cc => cc.CourseID == id);
            try
            {
                if (c != null)
                {
                    c.CourseStateID = this.db.GetPassiveCourseState();
                    this.db.SubmitChanges();
                }

                return RedirectToAction("Index");
            }
            catch
            {
                return View(c);
            }
        }


        public ActionResult Download(int id)
        {
            CourseContent cc = this.db.CourseContents.FirstOrDefault(c => c.ContentID == id);
            if (cc == null)
            {
                return null;
            }

            ContentDisposition cd = new System.Net.Mime.ContentDisposition
            {
                FileName = cc.FileName,

                // always prompt the user for downloading, set to true if you want 
                // the browser to try to show the file inline
                Inline = true,
            };
            Response.AppendHeader("Content-Disposition", cd.ToString());
            return File(cc.Content.ToArray(), cc.MimeType);
        }


    }
}
